package com.wzxy.nc.realm;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;  
import org.apache.shiro.authc.AuthenticationInfo;  
import org.apache.shiro.authc.AuthenticationToken;  
import org.apache.shiro.authc.SimpleAuthenticationInfo;  
import org.apache.shiro.authc.UsernamePasswordToken;  
import org.apache.shiro.authz.AuthorizationInfo;  
import org.apache.shiro.authz.SimpleAuthorizationInfo;  
import org.apache.shiro.realm.AuthorizingRealm;  
import org.apache.shiro.subject.PrincipalCollection;  
import org.springframework.beans.factory.annotation.Autowired;

import com.wzxy.nc.dao.ISysUserDao;
import com.wzxy.nc.entity.SysRole;
import com.wzxy.nc.entity.SysUser;
import com.wzxy.nc.util.HttpSessionUtil;
import com.wzxy.nc.util.SysConstant;
  
public class MyRealm extends AuthorizingRealm implements Serializable {
	
    private static final long serialVersionUID = 1L;
    
    @Autowired
    private ISysUserDao userDao;
      
     /**
      * 权限认证，为当前登录的Subject授予角色和权限
      */
     @Override  
     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    	//获取当前登录输入的用户名
    	String loginName = (String)super.getAvailablePrincipal(principalCollection);
    	//到数据库查是否有此对象
    	SysUser user = userDao.findByUsername(loginName);
    	if(user != null) {
    		//权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
    		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    		//用户的角色集合
    		info.setRoles(user.getRoleName());
    		//用户的角色对应的所有权限，如果只使用角色定义访问权限
    		Set<SysRole> roles = user.getRoles();
    		Iterator<SysRole> it = roles.iterator();
    		System.out.print("用户具有的角色:");
    		while(it.hasNext()){
    			SysRole role = it.next();
    			info.addStringPermissions(role.getPermissionsName());
    			System.out.print(role.getRoleName() + " ");
    		}
    		System.out.println();
    		return info;
    	}
        return null;  
     }
     
     /**
      * 登陆认证  
      */
     @Override  
     protected AuthenticationInfo doGetAuthenticationInfo(  
             AuthenticationToken authenticationToken) throws AuthenticationException {  
    	 
    	//UsernamePasswordToken对象用来存放提交的登录信息
    	UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    	//查出是否有此用户
    	SysUser user = userDao.findByUsername(token.getUsername());
    	if(user != null) {
    		//登陆成功,把用户的信息放到session中
    		HttpSessionUtil.put(SysConstant.LOGIN_USER, user);
    		return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),getName());
    	}
    	return null;
     }
      
}  